﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Net;
using HtmlAgilityPack;
using WebArchiveCopier.IO;

namespace WebArchiveCopier
{
	public class ItemCaptureCalendarPage : WebPage
	{
		private Regex pattern = new Regex(@"_(?<year>\d{4}):-?\d+:(?!0{12})\w{12}");
		private string itemAddress;

		public ItemCaptureCalendarPage(string address, IDataManager dataManager) :
			base(WebArchive.GetItemCaptureCalendarAddress(address), dataManager)
		{
			itemAddress = address;
		}

		public ItemCaptureCalendarPage(string address, string year, IDataManager dataManager) :
			base(WebArchive.GetItemCaptureCalendarAddress(address, year), dataManager)
		{
			itemAddress = address;
		}

		public IEnumerable<ItemCaptureCalendarPage> Pages
		{
			get
			{
				var node = Document.DocumentNode.SelectSingleNode("//img[@id='sparklineImgId']");
				if (node != null)
				{
					var src = node.GetAttributeValue("src", null);
					if (src != null)
					{
						foreach (Match match in pattern.Matches(src))
						{
							yield return new ItemCaptureCalendarPage(itemAddress, match.Groups["year"].Value, DataManager);
						}
					}
				}
			}
		}

		public IEnumerable<DateTime> Captures
		{
			get
			{
				var popNodes = Document.DocumentNode.SelectNodes("//div[@class='pop']");

				if (popNodes != null)
				{
					foreach (var popNode in popNodes)
					{
						var date = popNode.SelectSingleNode("./h3[1]").InnerText;
						var nodes = popNode.SelectNodes("./ul/li");

						foreach (var node in nodes)
						{
							var link = node.SelectSingleNode("./a");
							yield return DateTime.Parse(string.Format("{0} {1}", date, link.InnerText));
						}
					}
				}
			}
		}
	}
}
